// static/script.js

document.addEventListener('DOMContentLoaded', function() {
    // DOM elements
    const cardJsonTextarea = document.getElementById('cardJson');
    const saveTemplateBtn = document.getElementById('saveTemplateBtn');
    const previewBtn = document.getElementById('previewBtn');
    const sendBtn = document.getElementById('sendBtn');
    const batchSendBtn = document.getElementById('batchSendBtn');
    const previewArea = document.getElementById('previewArea');
    const templateNameInput = document.getElementById('templateName');
    const templateCategorySelect = document.getElementById('templateCategory');
    const templateTagsInput = document.getElementById('templateTags');
    const savedTemplatesDiv = document.getElementById('savedTemplates');
    const searchInput = document.getElementById('searchInput');
    const categoryFilter = document.getElementById('categoryFilter');
    const tagFilter = document.getElementById('tagFilter');
    const searchBtn = document.getElementById('searchBtn');
    const clearSearchBtn = document.getElementById('clearSearchBtn');
    const versionControlPanel = document.getElementById('versionControlPanel');
    const currentTemplateNameSpan = document.getElementById('currentTemplateName');
    const versionListDiv = document.getElementById('versionList');
    const showVersionsBtn = document.getElementById('showVersionsBtn');
    const hideVersionsBtn = document.getElementById('hideVersionsBtn');
    const restoreVersionBtn = document.getElementById('restoreVersionBtn');
    const importFileInput = document.getElementById('importFile');
    const importBtn = document.getElementById('importBtn');
    const exportBtn = document.getElementById('exportBtn');
    const clearEditorBtn = document.getElementById('clearEditorBtn');
    const batchCardsJsonTextarea = document.getElementById('batchCardsJson');
    const addSampleBatchBtn = document.getElementById('addSampleBatchBtn');
    const validateBatchBtn = document.getElementById('validateBatchBtn');
    const executeBatchSendBtn = document.getElementById('executeBatchSendBtn');
    const batchValidationResult = document.getElementById('batchValidationResult');
    const batchSendResults = document.getElementById('batchSendResults');
    const scheduleTimeInput = document.getElementById('scheduleTime');
    const scheduleWebhookUrlInput = document.getElementById('scheduleWebhookUrl');
    const scheduleSecretInput = document.getElementById('scheduleSecret');
    const scheduleCurrentCardBtn = document.getElementById('scheduleCurrentCardBtn');
    const scheduleLoadCurrentCardBtn = document.getElementById('scheduleLoadCurrentCardBtn');
    const scheduleResult = document.getElementById('scheduleResult');
    const refreshScheduledTasksBtn = document.getElementById('refreshScheduledTasksBtn');
    const scheduledTasksList = document.getElementById('scheduledTasksList');
    const historySearch = document.getElementById('historySearch');
    const historyTypeFilter = document.getElementById('historyTypeFilter');
    const refreshHistoryBtn = document.getElementById('refreshHistoryBtn');
    const historyList = document.getElementById('historyList');
    const confirmModal = new bootstrap.Modal(document.getElementById('confirmModal'));
    const confirmMessage = document.getElementById('confirmMessage');
    const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
    
    // JSON Editor with syntax highlighting
    let jsonEditor = null;
    const jsonEditorContainer = document.getElementById('jsonEditor');
    
    if (jsonEditorContainer) {
        // Create a contenteditable div for syntax highlighting
        const jsonEditorDiv = document.createElement('div');
        jsonEditorDiv.id = 'jsonEditorDiv';
        jsonEditorDiv.className = 'form-control json-editor';
        jsonEditorDiv.contentEditable = true;
        jsonEditorDiv.spellcheck = false;
        jsonEditorDiv.style.height = '400px';
        jsonEditorDiv.style.overflow = 'auto';
        jsonEditorDiv.style.fontFamily = 'monospace';
        jsonEditorDiv.style.whiteSpace = 'pre';
        
        // Replace textarea with contenteditable div
        jsonEditorContainer.parentNode.replaceChild(jsonEditorDiv, jsonEditorContainer);
        
        // Initialize with textarea content if available
        jsonEditorDiv.textContent = cardJsonTextarea.value;
        
        // Update textarea when content changes
        jsonEditorDiv.addEventListener('input', function() {
            cardJsonTextarea.value = this.textContent;
            highlightJson(this);
        });
        
        // Add syntax highlighting
        highlightJson(jsonEditorDiv);
        
        // Update editor when loading templates
        const originalLoadTemplate = window.loadTemplate;
        window.loadTemplate = function(name) {
            originalLoadTemplate(name);
            setTimeout(() => {
                if (jsonEditorDiv) {
                    highlightJson(jsonEditorDiv);
                }
            }, 100);
        };
        
        // Make jsonEditor reference available globally
        window.jsonEditor = jsonEditorDiv;
    }
    
    // Function to add syntax highlighting to JSON
    function highlightJson(element) {
        if (!element) return; // Check if element exists
        
        const originalValue = element.textContent;
        let jsonStr;
        
        try {
            // Try to parse and restringify to validate JSON
            jsonStr = JSON.stringify(JSON.parse(originalValue), null, 2);
        } catch (e) {
            // If it's not valid JSON, just return without highlighting
            element.innerHTML = escapeHtml(originalValue);
            return;
        }
        
        // Apply syntax highlighting to the JSON string
        element.innerHTML = syntaxHighlight(jsonStr);
    }
    
    // Function to escape HTML characters
    function escapeHtml(unsafe) {
        return unsafe
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }
    
    // Function to apply syntax highlighting
    function syntaxHighlight(json) {
        // Convert to text and then apply highlighting
        json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
        
        // Regular expressions to match JSON syntax
        return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
            let cls = 'json-number';
            if (/^"/.test(match)) {
                if (/:$/.test(match)) {
                    cls = 'json-key';
                } else {
                    cls = 'json-string';
                }
            } else if (/true|false/.test(match)) {
                cls = 'json-boolean';
            } else if (/null/.test(match)) {
                cls = 'json-null';
            }
            return '<span class="' + cls + '">' + match + '</span>';
        });
    }
    
    let templateToDelete = null;
    let allTags = new Set(); // Store all tags for filter
    let currentTemplateForVersion = null; // Track which template we're viewing versions for
    let selectedVersion = null; // Track which version is selected for restore
    
    // Predefined templates
    const predefinedTemplates = {
        text: {
            msgtype: "text",
            text: {
                content: "这是一条纯文本消息"
            }
        },
        image_text: {
            msgtype: "link", 
            link: {
                text: "这是一条图文消息的描述",
                title: "图文消息标题", 
                picUrl: "",
                messageUrl": "https://www.example.com"
            }
        },
        action_card: {
            msgtype: "actionCard",
            actionCard: {
                title: "操作卡片标题",
                text: "![image](https://www.dingtalk.com/logo.png)\n### 操作卡片\n您有一项待处理任务\n- 任务1: 内容描述\n- 任务2: 内容描述",
                btnOrientation: "0",
                btns": [
                    {
                        title: "确认操作",
                        actionURL": "https://www.dingtalk.com"
                    },
                    {
                        title: "取消操作", 
                        actionURL": "https://www.dingtalk.com"
                    }
                ]
            }
        },
        markdown: {
            msgtype: "markdown",
            markdown: {
                title: "Markdown卡片",
                text: "# 标题\n\n这是一段**加粗**的文本和*斜体*文本。\n\n- 列表项1\n- 列表项2\n\n[链接文本](https://www.example.com)"
            }
        },
        feed_card: {
            msgtype: "feedCard",
            feedCard: {
                links": [
                    {
                        title: "时代的火车向前开1",
                        messageURL": "https://www.example.com",
                        picURL": "https://www.dingtalk.com/logo.png"
                    },
                    {
                        title: "时代的火车向前开2",
                        messageURL": "https://www.example.com",
                        picURL": "https://www.dingtalk.com/logo.png"
                    }
                ]
            }
        },
        single_action_card: {
            msgtype: "actionCard",
            actionCard: {
                title: "进度提醒",
                text: "任务“项目周报”截至今天，请及时完成",
                hideAvatar: "0",
                btnOrientation: "0",
                singleTitle": "查看任务",
                singleURL": "https://www.example.com"
            }
        },
        oa_message: {
            msgtype: "oa",
            oa: {
                message_url": "https://www.example.com",
                head: {
                    bgcolor": "FFBBBBBB",
                    text": "审批通知"
                },
                body: {
                    title": "请假申请",
                    form": [
                        {"key": "申请人：", "value": "张三"},
                        {"key": "请假类型：", "value": "年假"},
                        {"key": "请假时间：", "value": "2023-01-01 至 2023-01-03"}
                    ],
                    rich": {
                        "num": "3",
                        "unit": "天"
                    },
                    content: "请假事由：回家探亲",
                    image": "https://www.dingtalk.com/logo.png",
                    file_count": "1",
                    author": "行政部"
                }
            }
        }
    };
    
    // Load saved templates and categories on page load
    loadSavedTemplates();
    loadCategories();
    
    // Event listeners for search functionality
    searchBtn.addEventListener('click', performSearch);
    clearSearchBtn.addEventListener('click', function() {
        searchInput.value = '';
        categoryFilter.value = '';
        tagFilter.value = '';
        loadSavedTemplates(); // Reload all templates
    });
    
    // Also allow Enter key to trigger search
    searchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            performSearch();
        }
    });
    
    // Event listeners for version control functionality
    showVersionsBtn.addEventListener('click', function() {
        if (currentTemplateForVersion) {
            showVersionControl(currentTemplateForVersion);
        } else {
            alert('请先加载一个模板以查看其版本');
        }
    });
    
    hideVersionsBtn.addEventListener('click', function() {
        hideVersionControl();
    });
    
    restoreVersionBtn.addEventListener('click', function() {
        if (currentTemplateForVersion && selectedVersion !== null) {
            restoreTemplateVersion(currentTemplateForVersion, selectedVersion);
        } else {
            alert('请先选择要恢复的版本');
        }
    });
    
    // Event listeners for import/export functionality
    importBtn.addEventListener('click', function() {
        const file = importFileInput.files[0];
        if (!file) {
            alert('请选择一个JSON文件进行导入');
            return;
        }
        
        const reader = new FileReader();
        reader.onload = function(e) {
            try {
                const templateData = JSON.parse(e.target.result);
                
                fetch('/api/templates/import', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(templateData)
                })
                .then(response => response.json())
                .then(data => {
                    if (response.ok) {
                        alert('模板导入成功');
                        // Reset the file input
                        importFileInput.value = '';
                        // Reload templates list
                        loadSavedTemplates();
                    } else {
                        alert(`导入失败: ${data.message || '未知错误'}`);
                    }
                })
                .catch(error => {
                    console.error('Import error:', error);
                    alert('导入失败: ' + error.message);
                });
            } catch (error) {
                alert('文件格式错误，不是有效的JSON文件');
            }
        };
        reader.readAsText(file);
    });
    
    exportBtn.addEventListener('click', function() {
        const templateName = templateNameInput.value.trim();
        if (!templateName) {
            alert('请输入模板名称或加载一个已存在的模板');
            return;
        }
        
        // Export the current template
        fetch(`/api/templates/${encodeURIComponent(templateName)}/export`)
        .then(response => response.json())
        .then(data => {
            // Create a downloadable file
            const jsonString = JSON.stringify(data, null, 2);
            const blob = new Blob([jsonString], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            
            const a = document.createElement('a');
            a.href = url;
            a.download = `${templateName}_export.json`;
            document.body.appendChild(a);
            a.click();
            
            // Clean up
            setTimeout(() => {
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);
            }, 0);
        })
        .catch(error => {
            console.error('Export error:', error);
            alert('导出失败: ' + error.message);
        });
    });
    
    // Clear editor button
    clearEditorBtn.addEventListener('click', function() {
        if (confirm('确定要清空编辑器吗？此操作不可恢复。')) {
            cardJsonTextarea.value = JSON.stringify({
                "msgtype": "text",
                "text": {
                    "content": "这是清空后的新内容"
                }
            }, null, 2);
        }
    });
    
    // Batch send functionality
    addSampleBatchBtn.addEventListener('click', function() {
        const sampleConfig = [
            {
                "webhook_url": "https://oapi.dingtalk.com/robot/send?access_token=YOUR_TOKEN",
                "secret": "YOUR_SECRET",  // Optional
                "content": {
                    "msgtype": "text",
                    "text": {
                        "content": "这是批量发送的示例消息1"
                    }
                }
            },
            {
                "webhook_url": "https://oapi.dingtalk.com/robot/send?access_token=ANOTHER_TOKEN",
                "content": {
                    "msgtype": "markdown",
                    "markdown": {
                        "title": "Markdown消息",
                        "text": "# 这是批量发送的示例消息2\n\n这是一条**加粗**的文本。"
                    }
                }
            }
        ];
        
        batchCardsJsonTextarea.value = JSON.stringify(sampleConfig, null, 2);
    });
    
    validateBatchBtn.addEventListener('click', function() {
        try {
            const batchData = JSON.parse(batchCardsJsonTextarea.value);
            
            if (!Array.isArray(batchData)) {
                throw new Error("'cards' must be an array");
            }
            
            // Check each item in the array
            for (let i = 0; i < batchData.length; i++) {
                const card = batchData[i];
                if (!card.content) {
                    throw new Error(`Item ${i} is missing 'content' property`);
                }
                if (!card.webhook_url) {
                    console.warn(`Item ${i} is missing 'webhook_url', will use default`);
                }
            }
            
            batchValidationResult.className = 'alert alert-success';
            batchValidationResult.style.display = 'block';
            batchValidationResult.textContent = `验证成功！共 ${batchData.length} 个发送任务。`;
        } catch (error) {
            batchValidationResult.className = 'alert alert-danger';
            batchValidationResult.style.display = 'block';
            batchValidationResult.textContent = `验证失败: ${error.message}`;
        }
    });
    
    executeBatchSendBtn.addEventListener('click', function() {
        try {
            const batchData = JSON.parse(batchCardsJsonTextarea.value);
            
            if (!Array.isArray(batchData)) {
                alert("'cards' must be an array");
                return;
            }
            
            // Execute batch send
            fetch('/api/batch-send', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ cards: batchData })
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    batchSendResults.innerHTML = `<div class="alert alert-danger">批量发送失败: ${data.error}</div>`;
                    return;
                }
                
                // Display results
                const resultsHtml = data.results.map((result, index) => {
                    const statusClass = result.status === 'success' ? 'alert-success' : 'alert-danger';
                    const statusText = result.status === 'success' ? '成功' : '失败';
                    return `
                        <div class="alert ${statusClass} my-1">
                            <strong>任务 ${index + 1}:</strong> ${statusText}
                            ${result.result ? `<br><small>${JSON.stringify(result.result)}</small>` : ''}
                            ${result.message ? `<br><small>错误: ${result.message}</small>` : ''}
                        </div>
                    `;
                }).join('');
                
                batchSendResults.innerHTML = `
                    <h6>发送结果:</h6>
                    <div class="alert alert-info">
                        ${data.message}
                    </div>
                    ${resultsHtml}
                `;
            })
            .catch(error => {
                batchSendResults.innerHTML = `<div class="alert alert-danger">请求失败: ${error.message}</div>`;
            });
        } catch (error) {
            alert(`批量发送配置格式错误: ${error.message}`);
        }
    });
    
    // Schedule send functionality
    scheduleLoadCurrentCardBtn.addEventListener('click', function() {
        try {
            // Parse the current content in the editor
            const currentContent = JSON.parse(cardJsonTextarea.value);
            
            // Validate that it's a valid card content
            if (!currentContent.msgtype) {
                alert('当前编辑器内容不是有效的钉钉卡片格式');
                return;
            }
            
            alert('当前卡片内容已加载到定时发送区域，可设置定时时间');
        } catch (error) {
            alert('当前编辑器内容不是有效的JSON格式: ' + error.message);
        }
    });
    
    scheduleCurrentCardBtn.addEventListener('click', function() {
        const scheduledTime = scheduleTimeInput.value;
        const webhookUrl = scheduleWebhookUrlInput.value.trim() || null;
        const secret = scheduleSecretInput.value.trim() || null;
        
        if (!scheduledTime) {
            alert('请选择定时发送时间');
            return;
        }
        
        try {
            // Parse the current content in the editor
            const currentContent = JSON.parse(cardJsonTextarea.value);
            
            // Validate that it's a valid card content
            if (!currentContent.msgtype) {
                alert('当前编辑器内容不是有效的钉钉卡片格式');
                return;
            }
            
            // Prepare the schedule request
            const scheduleData = {
                scheduled_time: new Date(scheduledTime).toISOString(),
                content: currentContent
            };
            
            if (webhookUrl) scheduleData.webhook_url = webhookUrl;
            if (secret) scheduleData.secret = secret;
            
            // Send schedule request
            fetch('/api/schedule-send', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(scheduleData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    scheduleResult.className = 'alert alert-danger';
                    scheduleResult.style.display = 'block';
                    scheduleResult.textContent = `定时发送失败: ${data.error}`;
                } else {
                    scheduleResult.className = 'alert alert-success';
                    scheduleResult.style.display = 'block';
                    scheduleResult.innerHTML = `
                        <strong>定时发送设置成功!</strong><br>
                        任务ID: ${data.task_id}<br>
                        发送时间: ${new Date(data.scheduled_time).toLocaleString()}
                    `;
                    
                    // Clear the inputs
                    scheduleTimeInput.value = '';
                    scheduleWebhookUrlInput.value = '';
                    scheduleSecretInput.value = '';
                }
            })
            .catch(error => {
                scheduleResult.className = 'alert alert-danger';
                scheduleResult.style.display = 'block';
                scheduleResult.textContent = `请求失败: ${error.message}`;
            });
        } catch (error) {
            alert('当前编辑器内容不是有效的JSON格式: ' + error.message);
        }
    });
    
    // Refresh scheduled tasks list
    refreshScheduledTasksBtn.addEventListener('click', loadScheduledTasks);
    
    // Load scheduled tasks list
    function loadScheduledTasks() {
        fetch('/api/scheduled-tasks')
        .then(response => response.json())
        .then(data => {
            if (data.tasks.length === 0) {
                scheduledTasksList.innerHTML = '<p class="text-muted">暂无定时任务</p>';
                return;
            }
            
            // Group tasks by status
            const statusGroups = {
                'scheduled': [],
                'executing': [],
                'completed': [],
                'failed': [],
                'cancelled': []
            };
            
            data.tasks.forEach(task => {
                if (statusGroups[task.status]) {
                    statusGroups[task.status].push(task);
                } else {
                    // Group all other statuses under 'other'
                    if (!statusGroups.other) statusGroups.other = [];
                    statusGroups.other.push(task);
                }
            });
            
            let tasksHtml = '';
            
            // Render each status group
            Object.entries(statusGroups).forEach(([status, tasks]) => {
                if (tasks.length > 0) {
                    const statusText = {
                        'scheduled': '待执行',
                        'executing': '执行中',
                        'completed': '已完成',
                        'failed': '已失败',
                        'cancelled': '已取消'
                    }[status] || status;
                    
                    const statusClass = {
                        'scheduled': 'primary',
                        'executing': 'warning',
                        'completed': 'success',
                        'failed': 'danger',
                        'cancelled': 'secondary'
                    }[status] || 'dark';
                    
                    tasksHtml += `
                        <div class="card mb-3">
                            <div class="card-header bg-${statusClass} text-white">
                                ${statusText} (${tasks.length})
                            </div>
                            <div class="card-body">
                    `;
                    
                    tasks.forEach(task => {
                        tasksHtml += `
                            <div class="task-item p-2 border mb-2">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <strong>任务ID:</strong> ${task.id}<br>
                                        <strong>内容类型:</strong> ${task.content.msgtype || '未知'}<br>
                                        <strong>计划时间:</strong> ${new Date(task.scheduled_time).toLocaleString()}<br>
                                        ${task.status === 'scheduled' || task.status === 'executing' ? 
                                            `<strong>创建时间:</strong> ${new Date(task.created_at).toLocaleString()}<br>` : 
                                            `<strong>完成时间:</strong> ${task.completed_at ? new Date(task.completed_at).toLocaleString() : 'N/A'}<br>`}
                                        ${task.error ? `<strong>错误:</strong> ${task.error}<br>` : ''}
                                    </div>
                                    <div>
                                        ${task.status === 'scheduled' ? 
                                            `<button class="btn btn-sm btn-danger cancel-task-btn" data-task-id="${task.id}">取消任务</button>` : 
                                            ''}
                                    </div>
                                </div>
                            </div>
                        `;
                    });
                    
                    tasksHtml += '</div></div>';
                }
            });
            
            scheduledTasksList.innerHTML = tasksHtml;
            
            // Add event listeners for cancel buttons
            document.querySelectorAll('.cancel-task-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const taskId = this.getAttribute('data-task-id');
                    cancelScheduledTask(taskId);
                });
            });
        })
        .catch(error => {
            scheduledTasksList.innerHTML = `<div class="alert alert-danger">加载定时任务失败: ${error.message}</div>`;
        });
    }
    
    // Cancel scheduled task
    function cancelScheduledTask(taskId) {
        if (!confirm(`确定要取消任务 ${taskId} 吗？`)) {
            return;
        }
        
        fetch(`/api/scheduled-tasks/${taskId}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                alert(`取消任务失败: ${data.error}`);
            } else {
                alert(`任务 ${taskId} 已取消`);
                loadScheduledTasks(); // Refresh the list
            }
        })
        .catch(error => {
            alert(`取消任务请求失败: ${error.message}`);
        });
    }
    
    // Event listeners for template selection
    function setupTemplateSelection() {
        document.querySelectorAll('.card-template').forEach(template => {
            template.addEventListener('click', function() {
                // Remove selected class from all templates
                document.querySelectorAll('.card-template').forEach(t => {
                    t.classList.remove('selected');
                });
                
                // Add selected class to clicked template
                this.classList.add('selected');
                
                // Set JSON content based on selected template
                const templateType = this.getAttribute('data-template');
                if (predefinedTemplates[templateType]) {
                    cardJsonTextarea.value = JSON.stringify(predefinedTemplates[templateType], null, 2);
                    
                    // Add syntax highlighting if jsonEditor is available
                    if (window.jsonEditor) {
                        window.jsonEditor.textContent = cardJsonTextarea.value;
                        highlightJson(window.jsonEditor);
                    }
                }
            });
        });
    }
    
    // Call setup function after DOM is fully loaded
    setupTemplateSelection();
    
    // Load categories
    function loadCategories() {
        fetch('/api/categories')
        .then(response => response.json())
        .then(data => {
            templateCategorySelect.innerHTML = '<option value="">选择分类</option>';
            data.categories.forEach(category => {
                const option = document.createElement('option');
                option.value = category;
                option.textContent = category;
                templateCategorySelect.appendChild(option);
            });
        })
        .catch(error => {
            console.error('Error loading categories:', error);
        });
    }
    
    // Save template button event
    saveTemplateBtn.addEventListener('click', function() {
        const templateName = templateNameInput.value.trim();
        const templateCategory = templateCategorySelect.value || '默认分类';
        const templateTags = templateTagsInput.value.trim() ? 
            templateTagsInput.value.trim().split(',').map(tag => tag.trim()).filter(tag => tag) : 
            [];
            
        if (!templateName) {
            alert('请输入模板名称');
            return;
        }
        
        try {
            // Validate JSON
            JSON.parse(cardJsonTextarea.value);
        } catch (e) {
            alert('JSON格式不正确，请检查');
            return;
        }
        
        // Prepare data with category and tags
        const data = {
            content: JSON.parse(cardJsonTextarea.value),
            category: templateCategory,
            tags: templateTags
        };
        
        fetch(`/api/templates/${encodeURIComponent(templateName)}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(data => {
            alert('模板保存成功');
            templateNameInput.value = '';
            templateTagsInput.value = '';
            loadSavedTemplates(); // Refresh the list
        })
        .catch(error => {
            console.error('Error:', error);
            alert('保存失败');
        });
    });
    
    // Preview button event
    previewBtn.addEventListener('click', function() {
        try {
            const cardData = JSON.parse(cardJsonTextarea.value);
            previewCard(cardData);
        } catch (e) {
            alert('JSON格式不正确，无法预览');
        }
    });
    
    // Send button event
    sendBtn.addEventListener('click', function() {
        if (!confirm('确定要发送这张卡片吗？')) {
            return;
        }
        
        try {
            const cardData = JSON.parse(cardJsonTextarea.value);
            
            fetch('/api/send', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(cardData)
            })
            .then(response => response.json())
            .then(data => {
                alert('卡片发送成功');
            })
            .catch(error => {
                console.error('Error:', error);
                alert('发送失败');
            });
        } catch (e) {
            alert('JSON格式不正确，无法发送');
        }
    });
    
    // Load saved templates from backend
    function loadSavedTemplates() {
        fetch('/api/templates')
        .then(response => response.json())
        .then(data => {
            displayTemplates(data.templates);
        })
        .catch(error => {
            console.error('Error loading templates:', error);
            savedTemplatesDiv.innerHTML = '<p class="text-danger">加载模板失败</p>';
        });
    }
    
    // Perform search based on input, category, and tag filters
    function performSearch() {
        const query = searchInput.value.trim();
        const category = categoryFilter.value;
        const tag = tagFilter.value;
        
        let url = '/api/search?';
        const params = [];
        
        if (query) params.push(`q=${encodeURIComponent(query)}`);
        if (category) params.push(`category=${encodeURIComponent(category)}`);
        if (tag) params.push(`tag=${encodeURIComponent(tag)}`);
        
        if (params.length === 0) {
            // If no search parameters, load all templates
            loadSavedTemplates();
            return;
        }
        
        url += params.join('&');
        
        fetch(url)
        .then(response => response.json())
        .then(data => {
            displayTemplates(data.templates);
        })
        .catch(error => {
            console.error('Error searching templates:', error);
            alert('搜索模板失败');
        });
    }
    
    // Load specific template
    function loadTemplate(name) {
        fetch(`/api/templates/${encodeURIComponent(name)}`)
        .then(response => response.json())
        .then(template => {
            cardJsonTextarea.value = JSON.stringify(template.content, null, 2);
            // Set category and tags if available
            if (template.category) {
                // Find and select the matching category option
                const categoryOption = Array.from(templateCategorySelect.options).find(
                    option => option.value === template.category
                );
                if (categoryOption) {
                    templateCategorySelect.value = template.category;
                } else {
                    // If category doesn't exist in dropdown, add it
                    const option = document.createElement('option');
                    option.value = template.category;
                    option.textContent = template.category;
                    templateCategorySelect.appendChild(option);
                    templateCategorySelect.value = template.category;
                }
            }
            if (template.tags && template.tags.length > 0) {
                templateTagsInput.value = template.tags.join(', ');
            }
            
            // Set current template for version control
            currentTemplateForVersion = name;
            currentTemplateNameSpan.textContent = name;
        })
        .catch(error => {
            console.error('Error loading template:', error);
            alert('加载模板失败');
        });
    }
    
    // Show version control panel for a template
    function showVersionControl(templateName) {
        currentTemplateForVersion = templateName;
        currentTemplateNameSpan.textContent = templateName;
        versionControlPanel.style.display = 'block';
        loadTemplateVersions(templateName);
    }
    
    // Hide version control panel
    function hideVersionControl() {
        versionControlPanel.style.display = 'none';
        currentTemplateForVersion = null;
        versionListDiv.innerHTML = '';
    }
    
    // Load versions for a specific template
    function loadTemplateVersions(templateName) {
        fetch(`/api/templates/${encodeURIComponent(templateName)}/versions`)
        .then(response => response.json())
        .then(data => {
            versionListDiv.innerHTML = '';
            
            if (data.versions.length === 0) {
                versionListDiv.innerHTML = '<p class="text-muted">暂无历史版本</p>';
                return;
            }
            
            data.versions.forEach(version => {
                const versionEl = document.createElement('div');
                versionEl.className = 'version-item p-2 border-bottom';
                versionEl.innerHTML = `
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <strong>版本 ${version.version}</strong>
                            <div class="small text-muted">${new Date(version.saved_at).toLocaleString()}</div>
                        </div>
                        <div>
                            <input type="radio" name="versionSelect" value="${version.version}" 
                                ${version.version === data.versions[0].version ? 'checked' : ''}>
                        </div>
                    </div>
                `;
                versionListDiv.appendChild(versionEl);
            });
            
            // Add event listeners for version selection
            document.querySelectorAll('input[name="versionSelect"]').forEach(radio => {
                radio.addEventListener('change', function() {
                    selectedVersion = parseInt(this.value);
                });
            });
            
            // Select the latest version by default
            if (data.versions.length > 0) {
                selectedVersion = data.versions[0].version;
            }
        })
        .catch(error => {
            console.error('Error loading template versions:', error);
            versionListDiv.innerHTML = '<p class="text-danger">加载版本失败</p>';
        });
    }
    
    // Restore a specific version
    function restoreTemplateVersion(templateName, version) {
        if (!confirm(`确定要恢复到版本 ${version} 吗？这将覆盖当前模板内容。`)) {
            return;
        }
        
        fetch(`/api/templates/${encodeURIComponent(templateName)}/versions/${version}/restore`, {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            alert(`已恢复到版本 ${version}`);
            // Reload the template content
            loadTemplate(templateName);
            // Reload the version list to show the restored version as latest
            loadTemplateVersions(templateName);
        })
        .catch(error => {
            console.error('Error restoring template version:', error);
            alert('恢复版本失败');
        });
    }
    
    // Function to display templates with enhanced tag support
    function displayTemplates(templates) {
        savedTemplatesDiv.innerHTML = '';
        
        if (templates.length === 0) {
            savedTemplatesDiv.innerHTML = '<p class="text-muted">未找到匹配的模板</p>';
            return;
        }
        
        templates.forEach(template => {
            const templateDiv = document.createElement('div');
            templateDiv.className = 'col-md-4 mb-2';
            // Format tags display
            const tagsDisplay = template.tags && template.tags.length > 0 ? 
                `<div class="tags-list small text-muted">标签: ${template.tags.join(', ')}</div>` : 
                '';
            templateDiv.innerHTML = `
                <div class="template-item">
                    <div>
                        <strong>${template.name}</strong>
                        <div class="text-muted small">类型: ${template.content.msgtype || 'unknown'}</div>
                        <div class="text-muted small">分类: ${template.category || '未分类'}</div>
                        ${tagsDisplay}
                    </div>
                    <div>
                        <button class="btn btn-sm btn-outline-primary load-btn" data-name="${template.name}">加载</button>
                        <button class="delete-template-btn" data-name="${template.name}">
                            <i class="fas fa-trash"></i> 删除
                        </button>
                    </div>
                </div>
            `;
            savedTemplatesDiv.appendChild(templateDiv);
        });
        
        // Update all available tags for filter
        updateAvailableTags(templates);
        
        // Add event listeners to load buttons
        document.querySelectorAll('.load-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const name = this.getAttribute('data-name');
                loadTemplate(name);
            });
        });
        
        // Add event listeners to delete buttons
        document.querySelectorAll('.delete-template-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const name = this.getAttribute('data-name');
                templateToDelete = name;
                confirmMessage.textContent = `确定要删除模板 "${name}" 吗？`;
                confirmModal.show();
            });
        });
    }
    
    // Update the available tags in the tag filter dropdown
    function updateAvailableTags(templates) {
        // Clear the tag filter dropdown except the first option
        tagFilter.innerHTML = '<option value="">所有标签</option>';
        
        // Collect all unique tags from the templates
        const tagsSet = new Set();
        templates.forEach(template => {
            if (template.tags && Array.isArray(template.tags)) {
                template.tags.forEach(tag => tagsSet.add(tag));
            }
        });
        
        // Add tags to the dropdown
        tagsSet.forEach(tag => {
            const option = document.createElement('option');
            option.value = tag;
            option.textContent = tag;
            tagFilter.appendChild(option);
        });
    }
    
    // Delete template
    function deleteTemplate(name) {
        fetch(`/api/templates/${encodeURIComponent(name)}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                alert(data.error);
            } else {
                alert('模板删除成功');
                loadSavedTemplates(); // Refresh the list
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('删除失败');
        });
    }
    
    // Event listener for confirm delete button
    confirmDeleteBtn.addEventListener('click', function() {
        if (templateToDelete) {
            deleteTemplate(templateToDelete);
            confirmModal.hide();
            templateToDelete = null;
        }
    });
    
    // Preview card function
    function previewCard(cardData) {
        let previewContent = '';
        
        switch(cardData.msgtype) {
            case 'text':
                previewContent = `
                    <div class="alert alert-info">
                        <strong>文本消息:</strong><br>
                        ${cardData.text.content}
                    </div>
                `;
                break;
            case 'link':
                previewContent = `
                    <div class="card">
                        <div class="card-body">
                            <h6 class="card-title">${cardData.link.title || '无标题'}</h6>
                            <p class="card-text">${cardData.link.text || '无描述'}</p>
                            <a href="${cardData.link.messageUrl}" class="btn btn-primary btn-sm">查看详情</a>
                        </div>
                    </div>
                `;
                break;
            case 'markdown':
                // For markdown, we'll render the text content directly
                previewContent = `
                    <div class="card">
                        <div class="card-body">
                            <h6 class="card-title">${cardData.markdown.title || '无标题'}</h6>
                            <div class="card-text">${formatMarkdown(cardData.markdown.text)}</div>
                        </div>
                    </div>
                `;
                break;
            case 'actionCard':
                previewContent = `
                    <div class="card">
                        <div class="card-body">
                            <h6 class="card-title">${cardData.actionCard.title || '无标题'}</h6>
                            <div class="card-text">${formatMarkdown(cardData.actionCard.text)}</div>
                            <div class="mt-3">
                                ${cardData.actionCard.btns ? cardData.actionCard.btns.map(btn => 
                                    `<button class="btn btn-sm btn-primary me-2">${btn.title}</button>`
                                ).join('') : 
                                (cardData.actionCard.singleTitle ? 
                                    `<button class="btn btn-sm btn-primary">${cardData.actionCard.singleTitle}</button>` : '')}
                            </div>
                        </div>
                    </div>
                `;
                break;
            case 'feedCard':
                const links = cardData.feedCard.links || [];
                previewContent = `
                    <div class="card">
                        <div class="card-body">
                            <h6 class="card-title">信息卡片</h6>
                            <div class="list-group">
                                ${links.map(link => `
                                    <a href="${link.messageURL}" class="list-group-item list-group-item-action">
                                        <div class="d-flex w-100 justify-content-between">
                                            <h6 class="mb-1">${link.title}</h6>
                                            <small>查看详情</small>
                                        </div>
                                        <p class="mb-1">点击以访问内容</p>
                                    </a>
                                `).join('')}
                            </div>
                        </div>
                    </div>
                `;
                break;
            case 'oa':
                const oaBody = cardData.oa.body || {};
                previewContent = `
                    <div class="card">
                        <div class="card-header" style="background-color: #${cardData.oa.head.bgcolor || 'ffffff'}; color: white;">
                            ${cardData.oa.head.text || 'OA消息'}
                        </div>
                        <div class="card-body">
                            <h6 class="card-title">${oaBody.title || '无标题'}</h6>
                            <ul class="list-group list-group-flush">
                                ${(oaBody.form || []).map(item => `
                                    <li class="list-group-item">
                                        <strong>${item.key}</strong> ${item.value}
                                    </li>
                                `).join('')}
                            </ul>
                            <p class="card-text mt-2">${oaBody.content || ''}</p>
                            <div class="mt-2">
                                ${oaBody.rich ? 
                                    `<span class="badge bg-secondary">${oaBody.rich.num}${oaBody.rich.unit}</span>` 
                                    : ''}
                            </div>
                        </div>
                        <div class="card-footer">
                            <small class="text-muted">${oaBody.author || ''}</small>
                        </div>
                    </div>
                `;
                break;
            default:
                previewContent = `<div class="alert alert-warning">不支持的卡片类型: ${cardData.msgtype}</div>`;
        }
        
        previewArea.innerHTML = previewContent;
    }
    
    // Simple markdown formatting function
    function formatMarkdown(text) {
        // Convert markdown headers to HTML headers
        let formatted = text.replace(/^### (.*$)/gim, '<h6>$1</h6>');
        formatted = formatted.replace(/^## (.*$)/gim, '<h5>$1</h5>');
        formatted = formatted.replace(/^# (.*$)/gim, '<h4>$1</h4>');
        
        // Convert bold and italic
        formatted = formatted.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
        formatted = formatted.replace(/\*(.*?)\*/g, '<em>$1</em>');
        
        // Convert links
        formatted = formatted.replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2">$1</a>');
        
        // Convert lists
        formatted = formatted.replace(/^- (.*$)/gim, '<li>$1</li>');
        if (formatted.includes('<li>')) {
            formatted = formatted.replace(/(<li>.*<\/li>)/gs, '<ul>$1</ul>');
        }
        
        return formatted;
    }
    
    // History functionality
    // Load history on page load
    loadSendHistory();
    
    // Event listeners for history functionality
    refreshHistoryBtn.addEventListener('click', loadSendHistory);
    historySearch.addEventListener('input', filterHistory);
    historyTypeFilter.addEventListener('change', filterHistory);
    
    // Load send history from backend
    function loadSendHistory() {
        historyList.innerHTML = '<p class="text-muted">正在加载历史记录...</p>';
        
        fetch('/api/send-history')
        .then(response => response.json())
        .then(data => {
            displayHistory(data.history);
        })
        .catch(error => {
            console.error('Error loading history:', error);
            historyList.innerHTML = '<p class="text-danger">加载历史记录失败</p>';
        });
    }
    
    // Display history records
    function displayHistory(history) {
        historyList.innerHTML = '';
        
        if (history.length === 0) {
            historyList.innerHTML = '<p class="text-muted">暂无发送历史记录</p>';
            return;
        }
        
        history.forEach(record => {
            const historyEl = document.createElement('div');
            historyEl.className = 'history-item p-2 border-bottom';
            
            // Format timestamp
            const timestamp = new Date(record.timestamp).toLocaleString();
            
            // Determine status class based on result
            const isSuccess = !record.result || !record.result.error;
            const statusClass = isSuccess ? 'text-success' : 'text-danger';
            const statusText = isSuccess ? '成功' : '失败';
            
            historyEl.innerHTML = `
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <strong class="${statusClass}">${record.msgtype || 'unknown'}</strong>
                        <div class="small text-muted">${timestamp}</div>
                        <div class="small">${statusText} - ${record.result?.errmsg || record.result?.message || 'N/A'}</div>
                    </div>
                    <div>
                        <button class="btn btn-sm btn-outline-primary view-history-btn" data-record='${JSON.stringify(record)}'>查看</button>
                        <button class="btn btn-sm btn-outline-danger delete-history-btn" data-id="${record.id}">删除</button>
                    </div>
                </div>
            `;
            historyList.appendChild(historyEl);
        });
        
        // Add event listeners for view and delete buttons
        document.querySelectorAll('.view-history-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const record = JSON.parse(this.getAttribute('data-record'));
                viewHistoryRecord(record);
            });
        });
        
        document.querySelectorAll('.delete-history-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const recordId = this.getAttribute('data-id');
                deleteHistoryRecord(recordId);
            });
        });
    }
    
    // Filter history based on search and type
    function filterHistory() {
        const searchTerm = historySearch.value.toLowerCase();
        const selectedType = historyTypeFilter.value;
        
        fetch('/api/send-history')
        .then(response => response.json())
        .then(data => {
            let filteredHistory = data.history;
            
            // Apply search filter
            if (searchTerm) {
                filteredHistory = filteredHistory.filter(record => 
                    record.msgtype.toLowerCase().includes(searchTerm) ||
                    (record.result?.errmsg && record.result.errmsg.toLowerCase().includes(searchTerm)) ||
                    record.timestamp.toLowerCase().includes(searchTerm)
                );
            }
            
            // Apply type filter
            if (selectedType) {
                filteredHistory = filteredHistory.filter(record => 
                    record.msgtype === selectedType
                );
            }
            
            displayHistory(filteredHistory);
        })
        .catch(error => {
            console.error('Error filtering history:', error);
            historyList.innerHTML = '<p class="text-danger">过滤历史记录失败</p>';
        });
    }
    
    // View a history record in detail
    function viewHistoryRecord(record) {
        const detailContent = `
            <div class="modal fade" id="historyDetailModal" tabindex="-1">
                <div class="modal-dialog modal-xl">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">历史记录详情</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <h6>发送信息</h6>
                                    <p><strong>时间:</strong> ${new Date(record.timestamp).toLocaleString()}</p>
                                    <p><strong>消息类型:</strong> ${record.msgtype}</p>
                                    <p><strong>Webhook URL:</strong> ${record.webhook_url || 'N/A'}</p>
                                    <p><strong>状态:</strong> ${record.result?.errmsg ? '失败' : '成功'}</p>
                                    ${record.result ? \`<p><strong>结果:</strong> \${JSON.stringify(record.result)}</p>\` : ''}
                                </div>
                                <div class="col-md-6">
                                    <h6>卡片内容</h6>
                                    <pre class="bg-light p-2">\${JSON.stringify(record.content, null, 2)}</pre>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // Create temporary element to get modal HTML
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = detailContent;
        document.body.appendChild(tempDiv);
        
        // Show the modal
        const modal = new bootstrap.Modal(document.getElementById('historyDetailModal'));
        modal.show();
        
        // Remove modal when hidden
        document.getElementById('historyDetailModal').addEventListener('hidden.bs.modal', function () {
            this.remove();
        });
    }
    
    // Delete a history record
    function deleteHistoryRecord(recordId) {
        if (!confirm('确定要删除这条历史记录吗？此操作不可恢复。')) {
            return;
        }
        
        fetch(\`/api/send-history/\${recordId}\`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                alert(\`删除失败: \${data.error}\`);
            } else {
                alert('历史记录已删除');
                loadSendHistory(); // Refresh the list
            }
        })
        .catch(error => {
            alert(\`删除请求失败: \${error.message}\`);
        });
    }
});